package com.ysd.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.ysd.entity.User;
import com.ysd.util.DBManager;

public class UserDaoImpl {
	//增删改业务, 需要返回数据库受影响的行数
	public int addMessage(User user) {
		return DBManager.executeUpdate("insert into users(username,phone,email,content) values('"+user.getUsername()+"','"+user.getPhone()+"','"+user.getEmail()+"','"+user.getContent()+"')");
	}
	
	public int updateMessage(User user) {
		return DBManager.executeUpdate("update users set status='"+user.getStatus()+"' where id=" + user.getId());
	}
	
	public int updateMessageReply(User user) {
		return DBManager.executeUpdate("update users set status='已回复',reply='"+user.getReply()+"' where id="+user.getId());
	}
	
	public int delMessageByIds(String ids) { // 3121111,12
		return DBManager.executeUpdate("delete from users where id in(3121111,12)");
	}
	
	public List<User> getUsersByStatus(String status){
		List<User> list = new ArrayList<User>();
		
		Connection conn = DBManager.getConnection();
		Statement st = null;
		ResultSet rs = null;
		try {
			st = conn.createStatement();
			String sql = "select * from users where 1=1";
			if(status!=null && !status.equals("")) {
				sql += " and status='"+status+"'";
			}
			sql += " order by time desc";
			System.out.println(sql);
			rs = st.executeQuery(sql);
			while(rs.next()) {
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String phone = rs.getString("phone");
				String email = rs.getString("email");
				String content = rs.getString("content");
				String sta = rs.getString("status");
				String time = rs.getString("time");
				User user = new User(id, username, phone, email, content, sta, time);
				list.add(user);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			DBManager.closeAll(conn, st, rs);
		}
	}
	
	public User getUsersById(int id){
		User user = null;
		Connection conn = DBManager.getConnection();
		Statement st = null;
		ResultSet rs = null;
		try {
			st = conn.createStatement();
			String sql = "select * from users where id="+id;
			System.out.println(sql);
			rs = st.executeQuery(sql);
			while(rs.next()) {
				String username = rs.getString("username");
				String phone = rs.getString("phone");
				String email = rs.getString("email");
				String content = rs.getString("content");
				String sta = rs.getString("status");
				String time = rs.getString("time");
				user = new User(id, username, phone, email, content, sta, time);
			}
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			DBManager.closeAll(conn, st, rs);
		}
	}
}